package top.rish.universe.core.plugin;

import cn.hutool.core.util.ObjUtil;
import org.noear.luffy.executor.ExecutorFactory;
import org.noear.luffy.model.AFileModel;
import org.noear.solon.Solon;
import org.noear.solon.core.util.IoUtil;
import org.noear.solon.core.util.LogUtil;
import org.noear.solon.luffy.LuffyHandler;
import org.noear.solon.luffy.impl.JtFunctionLoader;
import org.noear.solon.luffy.impl.JtFunctionLoaderClasspath;
import org.noear.solon.luffy.impl.JtFunctionLoaderFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

public class UniFaasUtil {

    private static String fileContentGet(File file) {
        try {
            try (InputStream ins = new FileInputStream(file)) {
                String s = IoUtil.transferToString(ins, Solon.encoding());
                if(ObjUtil.isNotEmpty(s)){
                    s = s.replaceAll("\\uFEFF","");
                }
                return s;
            }
        } catch (IOException e) {
            LogUtil.global().warn(e.getMessage());
            return null;
        }
    }

    public static void installPluginFaas(UniversePluginEntity plugin ){
        String classFilePath = plugin.getClassFilePath();
        final String classPath = classFilePath+"/"+plugin.getId()+"/faas/";
        final String prefix = "/faas/"+plugin.getId()+"/";
        Solon.app().get(prefix+"**",  ctx -> {
            String pathNew = ctx.pathNew();
            File file = new File(classPath, pathNew.replaceAll("^"+prefix,"/"));
            if (file.exists() && file.isFile()) {
                AFileModel f = new AFileModel();
                f.content = fileContentGet(file);
                f.edit_mode = "javascript";
                f.path = pathNew;
                ExecutorFactory.exec(pathNew.replaceAll("[/-]", "_"), f, ctx);
            }

        });


    }
}
